package cn.ygh.bbo.framerwork.web.editor;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.util.Date;

/**
 * @author ygh
 * @Desc 日期格式转换
 * @date 2019/10/28
 */
public class DatePropertyEditorSupport extends PropertyEditorSupport {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM","yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"};

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isBlank(text)) {
            setValue(null);
        } else {
            if (isValidLong(text)){
                setValue(new Date(Long.parseLong(text)));
            }else {
                try {
                    setValue(DateUtils.parseDate(text, parsePatterns));
                } catch (ParseException e) {
                    logger.error(e.getMessage());
                    setValue(null);
                }
            }

        }
    }

    private boolean isValidLong(String str){
        try{
            long _v = Long.parseLong(str);
            return true;
        }catch(NumberFormatException e){
            return false;
        }
    }

    public static void main(String[] args) throws ParseException {
        String s="2019-11-04T16:00:00.000Z";
        System.out.println(DateUtils.parseDate(s, parsePatterns));
    }
}
